#include "Tools.h"
#include <locale>

//---------------------------------------------------------
// ITERATION:

template<class Iter, class Funct>
void for_all(Iter start, Iter end,
             Funct& functor) {
    for (Iter i = start; i != end; ++i)
        functor.action(*i);
}

template<class Iter, class Funct>
void for_all_pairs(Iter start1, Iter end1,
                   Iter start2, Iter end2,
                   Funct& functor) {
    for (Iter i = start1; i != end1; ++i)
        for (Iter j = start2; j != end2; j++)
            functor.action(*i, *j);
}

//---------------------------------------------------------
// Compare strings, ignoring case.
bool iequals(const std::string& s1,
             const std::string& s2) {
    int l1 = s1.length();
    int l2 = s2.length();
    if (l1 == l2) {
		std::locale loc;
        int l = l1 > l2 ? l1 : l2;
        for (int i = 0; i < l; i++)
            if (std::tolower(s1[i], loc) !=
                std::tolower(s2[i], loc))
                return false;
        return true;
    }
    return false;
}

bool iequals(const std::string& s1,
             const char *s2) {
    return iequals(s1, std::string(s2));
/*
    int l1 = s1.length();
    int i = 0;
    for (; i < l1; i++) {
        if (s2[i] == '\0')
            // s2 shorter
            return false;
        if (std::tolower(s1[i]) !=
            std::tolower(s2[i]))
            return false;
    }
    return s2[i] != '\0';
*/
}

bool iequals(const char *s1,
             const char *s2) {
    return iequals(std::string(s1), std::string(s2));

    // for (int i = 0; /* do nothing */ ; i++) {
    //     if (std::tolower(s1[i]) !=
    //         std::tolower(s2[i]))
    //         // tricky here:
    //         // If we hit '\0' at same time, exit on next if
    //         // if not, different length strings will have
    //         // different bytes at point where shorter one terminates first.
    //         return false;
    //     if (s1[i] == '\0')
    //         break;
    // }
    // return false;

}

bool iequals(const char *s1,
             const std::string& s2) {
    return iequals(s2, s1);
}
